package fw_db_wms

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"sync"
	"time"
	"wms-server/fw/fw_config"
	"wms-server/fw/fw_db/fw_db_wms/db_plugin"
	"wms-server/fw/fw_log"
)

var (
	db   *gorm.DB
	once sync.Once
)

func DbInit() {
	once.Do(func() {
		var err error
		dsn := fw_config.GetConfigHandler().GetString("db.wms.user") + ":" + fw_config.GetConfigHandler().GetString("db.wms.pwd") +
			"@tcp(" + fw_config.GetConfigHandler().GetString("db.wms.host") + ":" + fw_config.GetConfigHandler().GetString("db.wms.port") +
			")/" + fw_config.GetConfigHandler().GetString("db.wms.dbname") + "?charset=utf8mb4&parseTime=True&loc=Local&timeout=1000ms"
		db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
			SkipDefaultTransaction: true,
			NamingStrategy:         schema.NamingStrategy{SingularTable: true},
			Logger:                 logger.Default.LogMode(logger.Info),
		})
		if err == nil {
			fw_log.Slogger.Info("数据库打开成功")
		} else {
			fw_log.Slogger.Info("数据库打开失败")
			return
		}
		sqlDB, err := db.DB()
		if err != nil {
			fw_log.Slogger.Info("通用数据库对象获取失败")
			return
		}
		sqlDB.SetMaxOpenConns(100)
		sqlDB.SetMaxIdleConns(100)
		sqlDB.SetConnMaxIdleTime(time.Hour)
		if err != nil {
			sqlDB.Close()
			fw_log.Slogger.Info("数据库同步失败")
			return
		}
		db.Use(&db_wms_plugin.QueryBeforePlugin{})
		db.Use(&db_wms_plugin.CreateBeforePlugin{})
		db.Use(&db_wms_plugin.UpdateBeforePlugin{})
	})

}

func GetDB() *gorm.DB {
	return db
}
